#!/usr/bin/env bash
# Test stub for `doppler`. Returns env-configured canned values per key.
# Replaces real doppler on PATH during hermetic preflight tests so we
# assert the lib's missing/empty/all-present branches without touching the
# real Doppler API.
#
# State surface (per-test, via env):
#   DOPPLER_STUB_PRESENT_KEYS   CSV of keys whose `secrets get` returns a
#                               non-empty value (e.g. "DATABASE_URL,REDIS_URL").
#                               Unlisted keys exit non-zero (key missing).
#   DOPPLER_STUB_EMPTY_KEYS     CSV of keys that return the empty string AND
#                               exit 0 (set-but-empty -- the silent-403 case).
#   DOPPLER_STUB_VALUE          Value returned for present keys (default
#                               "stub-value"; tests rarely care).
#   DOPPLER_STUB_CALL_LOG       Path to append every call to (default unset =
#                               discard). Used for control-flow assertions.
#
# Recognized commands:
#   doppler secrets get <KEY> --plain --project <p> --config <c>
#       -> prints DOPPLER_STUB_VALUE and exits 0 if KEY is in PRESENT_KEYS
#       -> prints "" and exits 0           if KEY is in EMPTY_KEYS
#       -> prints nothing and exits 1      otherwise (key missing)
#
# Everything else exits 0 with no output (the lib only calls
# `secrets get`; future extensions can grow this).
set -uo pipefail

if [ -n "${DOPPLER_STUB_CALL_LOG:-}" ]; then
  printf 'doppler %s\n' "$*" >> "${DOPPLER_STUB_CALL_LOG}"
fi

# We only handle `secrets get <KEY> --plain ...`. Walk the argv to find the
# subcommand and the key (the first positional after `get`).
sub=""; verb=""; key=""
seen_secrets=0; seen_get=0
for a in "$@"; do
  if [ -z "$sub" ]; then
    sub="$a"
    [ "$sub" = "secrets" ] && seen_secrets=1
    continue
  fi
  if [ "$seen_secrets" = "1" ] && [ -z "$verb" ]; then
    verb="$a"
    [ "$verb" = "get" ] && seen_get=1
    continue
  fi
  if [ "$seen_get" = "1" ] && [ -z "$key" ] && [ "${a#--}" = "$a" ]; then
    key="$a"
    continue
  fi
done

# Unhandled subcommand -- exit 0, no output.
if [ "$seen_secrets" != "1" ] || [ "$seen_get" != "1" ] || [ -z "$key" ]; then
  exit 0
fi

# Helper: csv contains key?
_csv_has() {
  local csv="$1" needle="$2"
  case ",${csv}," in
    *",${needle},"*) return 0 ;;
    *)               return 1 ;;
  esac
}

present="${DOPPLER_STUB_PRESENT_KEYS:-}"
empty="${DOPPLER_STUB_EMPTY_KEYS:-}"
value="${DOPPLER_STUB_VALUE:-stub-value}"

if _csv_has "$present" "$key"; then
  printf '%s' "$value"
  exit 0
fi

if _csv_has "$empty" "$key"; then
  # Exit 0 with empty output -- the set-but-empty failure mode.
  printf ''
  exit 0
fi

# Key missing: real doppler exits non-zero with an error on stderr.
printf 'doppler: ERROR: secret not found: %s\n' "$key" >&2
exit 1
